package com.hgh.nettydemo.netty.nettyclient;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author: huguanghui
 * Created by huguanghui on 2018/6/18.
 * @Description:
 */
@Component("nettyClient")
@Order(10)
public class NettyClient {
    @Autowired
    @Qualifier("bootstrap")
    private Bootstrap bootstrap;

    @Value("${client.address}")
    private String address;

    @Value("${tcp.port}")
    private int port;


    private ChannelFuture channelFuture;

    //@PostConstruct
    public void start() throws Exception {

        channelFuture = bootstrap.connect(address, port).sync();
    }

    @PreDestroy
    public void stop() throws Exception {
        channelFuture.channel().closeFuture().sync();
    }

    public void sendMessage(String message){
        channelFuture.channel().writeAndFlush(message);
    }
}
